package com.ycl.javacore.thread.atomic;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Scratch {
    private static final AtomicInteger tokenCount = new AtomicInteger(0);
    public static final int capacity = 0;
    private static ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;

    //测试线程安全 
    public static void main(String[] args) {
        scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
        scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> {
            if (tokenCount.get() >= capacity) {
                tokenCount.incrementAndGet();
            }
        }, 0, 1, TimeUnit.SECONDS);

        Runnable runnable = () -> {
            while (true) {
                if (tokenCount.get() > 0) {
                    int i = tokenCount.decrementAndGet();
                    if (i < 0) {
                        System.out.println(i);
                    }
                }
            }
        };
        for (int i = 0; i < 100; i++) {
            new Thread(runnable).start();
        }
    }
}